package com.lgd.factoryattendance.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.lgd.factoryattendance.Bean.CustomSpinnerBean;
import com.lgd.factoryattendance.R;

import java.util.List;

/**
 * @Author lgd
 * @Date 2024/3/20 17:05
 * 自定义 spinner 样式
 */
public class CustomSpinnerAdapter extends BaseAdapter {
    private List<CustomSpinnerBean> customSpinnerBeanList;
    private Context mContext;
    private LayoutInflater layoutInflater;

    public CustomSpinnerAdapter(List<CustomSpinnerBean> customSpinnerBeanList, Context context) {
        this.customSpinnerBeanList = customSpinnerBeanList;
        this.mContext = context;
        this.layoutInflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return customSpinnerBeanList == null ? 0 : customSpinnerBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return customSpinnerBeanList == null ? null : customSpinnerBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            // 如果没有可重用的视图，则创建新视图并初始化ViewHolder
            convertView = layoutInflater.inflate(R.layout.custom_spinner_dept, parent, false);
            holder = new ViewHolder();
            holder.textView = (TextView) convertView.findViewById(R.id.deptName);
            convertView.setTag(holder); // 将ViewHolder附加到视图上，以便后续重用
        } else {
            // 如果有可重用的视图，则获取其ViewHolder
            holder = (ViewHolder) convertView.getTag();
        }
        // 使用ViewHolder来更新视图内容
        CustomSpinnerBean customSpinnerBean = customSpinnerBeanList.get(position);
        holder.textView.setText(customSpinnerBean.getDeptName());

        return convertView;
    }

    // ViewHolder类用于缓存视图的引用
    static class ViewHolder {
        TextView textView;
    }
}
